package com.studentstreet.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.studentstreet.R;
import com.studentstreet.entities.CartEntity;
import com.studentstreet.tools.HtmlTools;
import com.studentstreet.tools.dbhelper.OrderDBHelper;

/**
 * @author likebamboo
 * 
 */
public class CartAdapter extends BaseAdapter {
	private Context context = null;
	private List<CartEntity> mModel = new ArrayList<CartEntity>();
	private String userName = "";
	// handler用于更新EditText的Text
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 更新EditText的界面显示
			((EditText) msg.obj).setText(msg.arg1 + "");
		}
	};

	public CartAdapter(Context context, String userName) {
		super();
		this.context = context;
		this.userName = userName;
	}

	// 将数据添加到mModel中
	public void addCartList(List<CartEntity> cartList) {
		mModel.clear();
		for (CartEntity cart : cartList) {
			mModel.add(cart);
		}
	}

	// 从购物车中移出某一商品
	public boolean removeCart(int position) {
		// 如果当前的mModel的size<=position,说明删除会出错，return false
		if (mModel.size() <= position) {
			return false;
		}
		CartEntity cart = mModel.get(position);
		OrderDBHelper dbHelper = new OrderDBHelper(context);
		// 如果在数据库中删除成功
		if (dbHelper.delete(cart.getCart_id(), userName) > 0) {
			// 则删除mModel实体
			mModel.remove(position);
		}
		return true;
	}

	@Override
	public int getCount() {
		return mModel.size();
	}

	@Override
	public Object getItem(int position) {
		return mModel.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		if (view == null) {
			view = LayoutInflater.from(context).inflate(R.layout.cart_item,
					null);
		}
		CartEntity cart = mModel.get(position);
		// 大神经验：不可将这些TextView等控件声明为类成员，否则他们的监听器
		// 都会被最后一个Item的相应对象捕获
		TextView cartNameText = (TextView) view
				.findViewById(R.id.cart_goods_name);
		TextView cartPriceText = (TextView) view
				.findViewById(R.id.cart_goods_price);
		EditText cartCountEdit = (EditText) view
				.findViewById(R.id.cart_goods_count);
		Button cartCountDownButton = (Button) view
				.findViewById(R.id.cart_goods_count_down);
		Button cartCountUpButton = (Button) view
				.findViewById(R.id.cart_goods_count_up);
		// 设置商品名
		cartNameText.setText(HtmlTools.getGoods(cart.getCart_name(),
				cart.getCart_sellerName()));
		// 设置商品价格
		cartPriceText.setText(HtmlTools.getPrice(context, cart.getCart_price()
				+ ""));
		// 设置商品数量
		cartCountEdit.setText(cart.getCart_count() + "");
		// 设置商品名的监听器（应该跳转到相应的商品详情界面，暂未实现）
		cartNameText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(context, ((TextView) v).getText().toString(),
						Toast.LENGTH_SHORT).show();
			}
		});
		// 设置减少数量按钮监听器
		cartCountUpButton.setOnClickListener(new CountUpListener(cartCountEdit,
				cart.getCart_id()));
		// 设置增加数量按钮监听器
		cartCountDownButton.setOnClickListener(new CountDownListener(
				cartCountEdit, cart.getCart_id()));
		return view;
	}

	// 减少数量监听器
	class CountDownListener implements View.OnClickListener {
		private EditText et = null;
		private int goodsId = 0;

		public CountDownListener(EditText et, int id) {
			super();
			this.et = et;
			this.goodsId = id;
		}

		@Override
		public void onClick(View v) {
			OrderDBHelper dbHelper = new OrderDBHelper(context);
			// 更新数据库
			dbHelper.updateDown(goodsId, userName);
			// 启动数量查询更新线程
			new Thread(new GetCountThread(et, goodsId)).start();

		}
	}

	// 增加数量监听器
	class CountUpListener implements View.OnClickListener {
		private EditText et = null;
		private int goodsId = 0;

		public CountUpListener(EditText et, int id) {
			super();
			this.et = et;
			this.goodsId = id;
		}

		@Override
		public void onClick(View v) {
			OrderDBHelper dbHelper = new OrderDBHelper(context);
			// System.out.println("goodsId==========" + goodsId);
			// 更新数据库
			dbHelper.updateUp(goodsId, userName);
			// 启动数量查询更新线程
			new Thread(new GetCountThread(et, goodsId)).start();
		}
	}

	// 查询订单数量线程
	class GetCountThread implements Runnable {
		private EditText et = null;
		private int goodsId = 0;

		public GetCountThread(EditText et, int goodsId) {
			super();
			this.et = et;
			this.goodsId = goodsId;
		}

		@Override
		public void run() {
			// 取得数据库中相应订单项的数量
			OrderDBHelper db = new OrderDBHelper(context);
			int count = db.getCount(goodsId, userName);
			Message msg = handler.obtainMessage();
			msg.obj = et;
			msg.arg1 = count;
			// 发送消息通知界面更新
			handler.sendMessage(msg);
		}

	}
}
